package com.huilan.base.esl.service.rabbitmq;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class RabbitUtil {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            log.info("correlationData:{}", correlationData);
            log.info("ack:{}", ack);
            if (!ack)
                log.info("noAck:{}", ack);
        }
    };

    final RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
        @Override
        public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText, String exchange, String routingKey) {
            log.info("exchange:{}  routingKey:{}  replyCode:{}  replyText:{}", exchange, routingKey, replyCode, replyText);
        }
    };

    public void send(Object msg, String exchangeType) {
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnCallback(returnCallback);
        CorrelationData correlationData = new CorrelationData(System.nanoTime() + RandomUtil.randomString(10));
//        log.info("------Rabbit--Send-- trace :{} action:{} params: {} ", correlationData.getId(), exchangeType, msg);
        rabbitTemplate.convertAndSend(exchangeType, "springboot.any", msg, correlationData);
    }


}